﻿using System.Net;
using System.Runtime.InteropServices;
using System.Text.Json;

namespace WeAppsCenterOnlineSetup
{

    internal class Program
    {
        const string HTTP_GET_URL = "https://gitee.com/api/v5/repos/zhchmmx/we-apps-center/releases/latest";

        const string NET_VERSION_URL = "https://dotnetcli.azureedge.net/dotnet/WindowsDesktop/8.0/latest.version";


        static string downloadUrl;
        static void Main()
        {
            string latestVersion;
            if (!IsRuntimeInstalled())
            {
                //获取.NET运行时下载地址
                using (HttpClient getDotNetVersionClient = new HttpClient())
                {
                    latestVersion = getDotNetVersionClient.GetStringAsync(NET_VERSION_URL).Result;
                }
                string runtimeLink = $"https://dotnetcli.azureedge.net/dotnet/WindowsDesktop/{latestVersion}/windowsdesktop-runtime-{latestVersion}-win-x64.exe";
                Console.WriteLine("Preparing to download runtime...");
                //下载.NET运行时
                Downloader downloader = new Downloader();
                downloader.Download(runtimeLink);
            }
            //获取下载地址
            using (HttpClient getDownloadLinkClient = new HttpClient())
            {
                string responseBody = getDownloadLinkClient.GetStringAsync(HTTP_GET_URL).Result;
                Root root = JsonSerializer.Deserialize<Root>(responseBody, SourceGenerationContext.Default.Root);
                List<AssetsItem> assets = root.assets;
                downloadUrl = assets[0].browser_download_url;
            }
            Console.WriteLine("Preparing to download...");
            //下载文件
            Downloader downloader1 = new Downloader();
            downloader1.Download(downloadUrl);

            Console.ReadKey();
        }
        public static void Delete(string filename)
        {
            try
            {
                File.Delete(filename);
            }
            catch (Exception)
            {
                Delete(filename);
            }
        }

        private static bool IsRuntimeInstalled()
        {
            if (Directory.Exists("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App"))
            {
                foreach (var item in Directory.GetDirectories("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App"))
                {
                    string folderName = item.Replace("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App\\", "");
                    if (folderName.StartsWith("8."))
                    {
                        return true;
                    }
                }
                return false;
            }
            else
            {
                return false;
            }
        }
    }
}
